package course.dao.impl;

import course.dao.BaseDao;
import course.dao.TeaSubDao;
import course.pojo.entity.TeaSub;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HLF
 * @date 2022/7/1 9:53
 */
public class TeaSubDaoImpl extends BaseDao<TeaSub> implements TeaSubDao {
    @Override
    public int addTeaSub(TeaSub teaSub, Connection connection) {
        String sql = "insert into t_tea_sub values(?,?);";
        return update(connection, sql, teaSub.getTid(), teaSub.getSuid());
    }

    @Override
    public List<TeaSub> getList(Connection connection) {
        String sql = "select * from t_tea_sub;";
        return getBeanList(connection, sql);
    }

    @Override
    public List<TeaSub> getByTid(Integer tid, Connection connection) {
        String sql = "select * from t_tea_sub where tid = ?;";
        return getBeanList(connection, sql, tid);
    }

    @Override
    public List<TeaSub> getBySuid(Integer suid, Connection connection) {
        String sql = "select * from t_tea_sub where suid = ?;";
        return getBeanList(connection, sql, suid);
    }

    @Override
    public TeaSub getByTidAndSuid(Integer tid, Integer suid, Connection connection) {
        String sql = "select * from t_tea_sub where tid = ? and suid = ?;";
        return getOneBean(connection, sql, tid, suid);
    }

    @Override
    public int deleteByTidAndSuid(Integer tid, Integer suid, Connection connection) {
        String sql = "delete from t_tea_sub where tid = ? and suid = ?;";
        return update(connection, sql, tid, suid);
    }

    /**
     * 批量退课
     */
    @Override
    public int deleteSelect(List<Integer> ids, Integer tid, Connection connection) {
        String sql = "delete from t_tea_sub where suid in(?) and tid = " + tid;

        String sqlIN = ids.stream()
                .map(x -> String.valueOf(x))
                .collect(Collectors.joining(",", "(", ")"));

        sql = sql.replace("(?)", sqlIN);

        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            return preparedStatement.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
